package com.seeyon.apps.zhiwei.nbtest.util;

import cn.hutool.core.util.CharsetUtil;
import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson.JSON;
import lombok.extern.slf4j.Slf4j;
import okhttp3.*;

import javax.net.ssl.*;
import java.net.URL;
import java.security.SecureRandom;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
import java.util.Map;
import java.util.concurrent.TimeUnit;

@Slf4j
public class RestUtil {

    public static String post(String description, String url, Map params) throws Exception {
//        url = HttpUtil.encodeParams(url, CharsetUtil.CHARSET_UTF_8);
        URL reUrl= new URL(url);
        String content = JSON.toJSONString(params);
        log.info(description + "  url：" + reUrl);
        log.info(description + "  发送参数：" + content);
        OkHttpClient client = new OkHttpClient.Builder()
                .sslSocketFactory(createSSLSocketFactory())
                .hostnameVerifier(new TrustAllHostnameVerifier())
                .build();
        MediaType mediaType = MediaType.parse("application/json");
        RequestBody body = RequestBody.create(mediaType, content);
        Request request = new Request.Builder()
                .url(reUrl)
                .method("POST", body)
                .addHeader("Content-Type", "application/json")
                .build();
        Response response = client.newCall(request).execute();
        String res = response.body().string();
        log.info(description + "  回复参数：" + res);
        return res;
    }


    public static String postHttp(String description, String url, Map params) throws Exception {
        url = HttpUtil.encodeParams(url, CharsetUtil.CHARSET_UTF_8);
        String content = JSON.toJSONString(params);
        log.info(description + "  url：" + url);
        log.info(description + "  发送参数：" + content);
        OkHttpClient client = new OkHttpClient().newBuilder().build();
        MediaType mediaType = MediaType.parse("application/json");
        RequestBody body = RequestBody.create(mediaType, content);
        Request request = new Request.Builder()
                .url(url)
                .method("POST", body)
                .addHeader("Content-Type", "application/json")
                .build();
        Response response = client.newCall(request).execute();
        String res = response.body().string();
        log.info(description + "  回复参数：" + res);
        return res;
    }

    public static String get(String description, String url) throws Exception {
        url = HttpUtil.encodeParams(url, CharsetUtil.CHARSET_UTF_8);
        log.info(description + "  url：" + url);
        OkHttpClient client = new OkHttpClient().newBuilder().build();
        Request request = new Request.Builder()
                .url(url)
                .method("GET", null)
                .build();
        Response response = client.newCall(request).execute();
        String res = response.body().string();
        log.info(description + "  回复参数：" + res);
        return res;
    }

    public static String get(String description, String url, Map<String, Object> params) throws Exception {
        url = HttpUtil.urlWithForm(url, params, CharsetUtil.CHARSET_UTF_8, true);
        String content = JSON.toJSONString(params);
        log.info(description + "  url：" + url);
        log.info(description + "  发送参数：" + content);
        OkHttpClient client = new OkHttpClient().newBuilder().build();
        Request request = new Request.Builder()
                .url(url)
                .method("GET", null)
                .build();
        Response response = client.newCall(request).execute();
        String res = response.body().string();
        return res;
    }

    public static String put(String description, String url, Map params) throws Exception {
        url = HttpUtil.encodeParams(url, CharsetUtil.CHARSET_UTF_8);
        String content = JSON.toJSONString(params);
        log.info(description + "  url：" + url);
        log.info(description + "  发送参数：" + content);
        OkHttpClient client = new OkHttpClient().newBuilder()
                .connectTimeout(20, TimeUnit.SECONDS)
                .readTimeout(20, TimeUnit.SECONDS)
                .build();
        MediaType mediaType = MediaType.parse("application/json");
        RequestBody body = RequestBody.create(mediaType, content);
        Request request = new Request.Builder()
                .url(url)
                .method("PUT", body)
                .addHeader("Content-Type", "application/json")
                .build();
        Response response = client.newCall(request).execute();
        String res = response.body().string();
        log.info(description + "  回复参数：" + res);
        return res;
    }
//pkix 实现okhttp绕过 证书
    private static class TrustAllCerts implements X509TrustManager {
        @Override
        public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException {}

        @Override
        public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException {}

        @Override
        public X509Certificate[] getAcceptedIssuers() {return new X509Certificate[0];}
    }

    private static class TrustAllHostnameVerifier implements HostnameVerifier {
        @Override
        public boolean verify(String hostname, SSLSession session) {
            return true;
        }
    }

    private static SSLSocketFactory createSSLSocketFactory() {
        SSLSocketFactory ssfFactory = null;

        try {
            SSLContext sc = SSLContext.getInstance("TLS");
            sc.init(null,  new TrustManager[] { new TrustAllCerts() }, new SecureRandom());

            ssfFactory = sc.getSocketFactory();
        } catch (Exception e) {
        }

        return ssfFactory;
    }
}
